package com.kim.logs.context;

import com.alibaba.fastjson.JSONObject;
import com.kim.logs.eneity.MethodLogInfo;
import com.kim.logs.util.LogComponentConstant;
import com.kim.logs.util.TimeCostEnum;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Deacription TODO
 * @Author jianhua.hong
 * @Date 2020/4/2 18:33
 **/
public abstract class AbstractLogHandler {
    protected HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request;
    }
    protected void processRequestTraceId() {
        HttpServletRequest request = this.getRequest();
        String traceId = request.getHeader(LogComponentConstant.TRACE_ID);
        if (StringUtils.isBlank(traceId)) {
//            traceId = RequestSeqHelper.nextId();
            traceId = String.valueOf(UUID.randomUUID());
        }
        RequestLogContext.addTraceId(traceId);
    }
    protected boolean isOutPutLog(Object[] params) {
        boolean outputMark = this.isMultilFileMark(params);
        if (outputMark) {
            return false;
        } else {
            return true;
        }
    }
    protected boolean isMultilFileMark(Object[] params) {
        boolean multilFileMark = false;
        for (Object param : params) {
            if (param instanceof MultipartFile) {
                multilFileMark = true;
                break;
            }
        }
        return multilFileMark;
    }
    protected String getTimeCostFlag(long cost) {
        String costFlag = TimeCostEnum.costMark(cost);
        return costFlag;
    }
    protected MethodLogInfo buildMethodInfo(JoinPoint point) {
        HttpServletRequest request = this.getRequest();
        String path = request.getRequestURL().toString();
        String className = point.getSignature().getDeclaringTypeName();
        String method = request.getMethod();
        String methodName = point.getSignature().getName();
        Object[] params = point.getArgs();
        boolean multilFileMark = this.isMultilFileMark(params);
        MethodLogInfo requestLogInfo = new MethodLogInfo();
        requestLogInfo.setPath(path);
        requestLogInfo.setClassName(className);
        requestLogInfo.setMethod(method);
        requestLogInfo.setMethodName(methodName);
        if (!multilFileMark) {
            String paramsStr = JSONObject.toJSONString(params);
            requestLogInfo.setParamsStr(paramsStr);
        } else {
            requestLogInfo.setMultiFileMark(true);
        }
        return requestLogInfo;
    }
}